//index.js
//获取应用实例
var App = getApp()
let amap = require("../../assets/plugins/map/index")
Page({
  data: {
    // qqhd: true,
    sbtid: 0,
    zxd: true,
    tp: [{
      id: 1,
      img: "1111111"
    }, {
      id: 2,
      img: "2222"
    }, {
      id: 3,
      img: "3333"
    }, ],
    tid: [1],


    yaoqingyouli: false,
    activeIndex: 1,
    page: 0,
    pageSize: 10,
    isLastPage: false,
    tips: '上拉加载更多',
    commentsList: [],
    currentAddress: '',
    indicatorDots: !0,
    autoplay: true,
    interval: 3000,
    duration: 1000,
    swiperList: [],
    showCar: false,
    userInfo: {},
    userId: '',
    goods: {},
    prompt: {
      hidden: !0,
    },
    isFirst: true,
    msgList: [],
    comments: {},
    showCoupons: false,
    couponsList: [],
    receiveStatus: true,
    code: '', // 验证码
    phone: '',
    heavyId: 0, // 大客户ID
    isSendCode: false, // 是否已经发送了验证码
    text: '获取验证码', // 获取验证码按钮的文字
    invitationUserId: 0, // 邀请人的userId
    invitationSellerId: 0, // 邀请人的sellerId
    isShow: true, // 判断是否显示绑定手机号
    url: '',
    lng: '',
    lat: '',
    sendCode: ''
  },
  onLoad(options) {



    // setTimeout(() => {
    //   this.setData({ focus: true })
    // }, 3000)
    console.log(options, "options")
    // console.log("[onLaunch] 本次场景值:", options.scene)
    // 验证大客户
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);

      this.setData({
        heavyId: scene,
        isShow: true
      });
      //根据大客户ID验证传递过来的大客户是否可用
      this.getheavyShop(scene);
    } else {
      this.setData({
        isShow: false
      });
    }

    // 验证是否是被邀请过来的
    if (options.userId) {
      this.setData({
        invitationSellerId: options.sellerId,
        invitationUserId: options.userId
      });
    }
    setTimeout(() => {
      let userId = wx.getStorageSync('userId');
      App.HttpService.verification({
        userId: userId
      }).then(res => {


        if (res.data.code == 200) {
          this.setData({
            // false
            isShow: true
          });
        } else {
          this.setData({
            isShow: true
          });
        }
      });
    }, 1000);
    // 获取当前定位
    wx.getLocation({
      type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
      success: (res) => {

        var cc = this.getRegeo(res.longitude + ',' + res.latitude, true) //res.longitude + ',' + res.latitude' 116.82209,38.3062'


        this.getRegeo(res.longitude + ',' + res.latitude, true) //res.longitude + ',' + res.latitude' 116.82209,38.3062'
      }

    })
    //评论
    //this.getComments(1);

    var _this = this
    var couponsId = options.couponsId
    //
    if (couponsId)
      wx.showModal({
        title: '温馨提示',
        content: '点击确定领取优惠券',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            _this.fangfa(couponsId)
          } else if (res.cancel) {
            console.log('用户点击取消')
            wx.showToast({
              title: '领取失败',
              icon: 'loading',
              duration: 1500
            })
          }
        }
      })

    // this.getComments(this.data.activeIndex)
    this.onReachBottom()


    //首页的诱导添加
    setTimeout(() => {
      this.setData({
        wai: true
      })
    }, 3000)
  },
  onShow(options) {
    console.log("6325124455")
    let position = wx.getStorageSync('position')
    let [lng, lat] = position.location.split(',')


    this.getAgent(lng, lat)
    let defaultCar = wx.getStorageSync('defaultCar')
    if (!defaultCar) {
      this.setData({
        url: '/pages/car/firstMenu/index'
      });
    } else {
      this.setData({
        url: '/pages/product/package/index'
      });
    }
    let {
      isFirst
    } = this.data
    if (isFirst) {
      this.getDefault()
    } else {
      if (defaultCar.carId != this.data.defaultCar.carId) {
        this.getDefault()
      }
    }

    this.setData({
      activeIndex: 1
    })
    this.onReachBottom();
    console.log("重复调用小程序演示")
  },

  run() { // 公告滚动
    var that = this
    var interval = setInterval(() => {
      if (-that.data.marqueeDistance < that.data.length) {
        that.setData({
          marqueeDistance: that.data.marqueeDistance - that.data.marqueePace,
        })
      } else {
        clearInterval(interval)
        that.setData({
          marqueeDistance: that.data.windowWidth
        })
        that.run()
      }
    }, that.data.intervalTime)
  },

  getNotice() {

    let agent = wx.getStorageSync('agent')
    App.HttpService.notice({
      sellerId: agent.id
    }).then(res => {
      let data = res.data.data
      console.log("3333333333333333333", "22222222222222", data)
      this.setData({
        msgList: data
      })
    })
  },
  getAgent(lng, lat, cb) {

// 青县经纬度
// 116.804306
// 38.583021

    App.HttpService.sellerCountry({
      lng: lng,
      lat: lat
    }).then(res => {

      cb && cb()
      let data = res.data
      let agent = {}

      if (data.code == 200) {

        let agent = {
          id: res.data.data.sellerId
        }


        //  agent.id = 1
        this.setData({
          agent
        });

        wx.setStorageSync('agent', agent);

        this.getBanner();
        this.getDefault();
        this.getNotice();
        this.getCouponsList();
        this.data.page = 0;
        this.data.isLastPage = false;
        let commentsList = [];
        this.setData({
          commentsList
        });

        this.getComments(this.data.activeIndex);



      } else {
        agent.id = ''
        wx.setStorageSync('agent', agent);
      }
    }).catch(e => {
      cb && cb()
    })
  },
  // 跳转到评价详情页面
  toDetail(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `../comments/detail/detail?id=${id}`,
    })
  },
  initData() {
    const goods = {
      items: [],
      total: '',
      params: {
        page: 1,
        pageCount: 10,
        sellerId: '',
        carModelId: ''
      }
    }
    this.setData({
      goods: goods
    })

  },
  getBanner() { // 获取轮播图
    let agent = wx.getStorageSync('agent')
    App.HttpService.getBanner({
      sellerId: agent.id
    }).then(res => {
      let data = res.data

      if (data.code == 200) {
        this.setData({
          swiperList: data.data
        })
      }
    })
  },

  // 领取优惠券
  fangfa: function (e) {
    console.log(e)
    App.HttpService.ling({
      couponsId: e,
      userId: wx.getStorageSync('userId')
    }).then(res => {
      console.log(res)
      var k = res.data.code
      if (k == 200) {
        wx.showToast({
          title: '领取成功',
          icon: 'success',
          duration: 1500
        })
      } else {
        var msg = res.data.msg
        wx.showToast({
          title: msg,
          icon: 'none',
          duration: 1500
        })
      }

    })
  },
  // 传送fromid
  fid: function (e) {
    // fromid
    let uid = wx.getStorageSync('userId')
    App.HttpService.fid({
      buyerId: uid,
      fromId: e
    }).then(res => {
      console.log(res)
    })

  },
  addCar() { // 添加车辆
    wx.navigateTo({
      url: '/pages/car/firstMenu/index'
    })
  },
  toCar() { //车型管理
    wx.navigateTo({
      url: '/pages/car/list/index'
    })
  },
  getDefault() { // 获取默认车辆
    let userId = wx.getStorageSync('userId')
    let agent = wx.getStorageSync('agent')

    App.HttpService.getDefault({
      userId: userId
    }).then(res => {
      let data = res.data
      if (data.code == 200) {
        if (JSON.stringify(data.data.carInfo) != '{}') {
          let carInfo = data.data.carInfo
          let carModel = data.data.carModel
          let info = carInfo.brandName + ' ' + carInfo.factoryName + ' ' + carInfo.modelName
          let defaultCar = {
            carInfo: info,
            carId: carModel.id, // 默认车辆id
            carModelId: carModel.carModelId, // 车辆 车型三级id
            carFactoryId: carInfo.factoryId, // 车辆 车系二级id
            miles: carModel.miles,
            linkman: carModel.linkman,
            phone: carModel.phone,
            carCode: carModel.carAreaCode + carModel.carAreaNo,
            brandId: carInfo.brandId
          }

          wx.setStorageSync('defaultCar', defaultCar)
          this.setData({
            defaultCar: defaultCar,
            showCar: true,
            isFirst: false
          })
          this.getMulti();
          this.initData();
          this.getPproduct();
          this.getMeal();
          this.getCouponsList();
          // this.data.page = 0;
          // this.data.isLastPage=false;
          // this.getComments(this.data.activeIndex);
        } else {
          this.setData({
            showCar: false
          })
        }
      }
    })
  },
  getPproduct() { // 获取商品列表
    let goods = this.data.goods
    let agent = wx.getStorageSync('agent')
    let defaultCar = this.data.defaultCar
    let params = goods.params
    params.sellerId = agent.id
    params.carModelId = defaultCar.carModelId
    App.HttpService.getPproduct(params).then(res => {
      let data = res.data.data
      goods.items = [...goods.items, ...data.productList]
      if (data.productList.length > 0) {
        params.page = params.page + 1
        goods.total = data.counts
      }
      this.setData({
        goods,
        'prompt.hidden': goods.items.length
      })
    })
  },
  getMulti() { // 获取拼团列表
    let params = {
      page: 1,
      pageCount: 10,
      sellerId: '',
      carModelId: ''
    }
    let agent = wx.getStorageSync('agent')
    let defaultCar = this.data.defaultCar
    params.sellerId = agent.id
    params.carModelId = defaultCar.carModelId
    if (agent.id != '') {
      App.HttpService.getMulti(params).then(res => {
        let data = res.data.data
        if (data.multiList.length > 1) {
          this.setData({
            multiList: [data.multiList[0], data.multiList[1]]
          })
        } else {
          this.setData({
            multiList: data.multiList
          })
        }
      })
    }
  },
  getMeal() { // 获取套餐
    let agent = wx.getStorageSync('agent')
    let {
      defaultCar
    } = this.data
    if (agent.id != '') {
      App.HttpService.mealDetail({
        carId: defaultCar.carId,
        sellerId: agent.id,
        userId: wx.getStorageSync('userId')

      }).then(res => {
        let data = res.data.data
        this.setData({
          packages: data.info,
          pack: data
        })
      })
    }
  },
  toProduct(e) { // 商品详情
    let {
      id
    } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/product/detail/detail?id=${id}`
    })
  },
  toMuDetail(e) { // 拼团详情
    let {
      id
    } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/group-buying/detail/index?id=${id}`
    })
  },
  getRegeo(location) {

    amap.getRegeo(location).then(res => {

      let data = res[0]
      let address = data.regeocodeData.pois[0]
      let addressComponent = data.regeocodeData.addressComponent
      let province = addressComponent.province
      let city = ''
      if (typeof addressComponent.city != 'string') {
        city = province
      } else {
        city = addressComponent.city
      }
      this.setData({
        currentAddress: address.name
      })

      wx.setStorageSync('position', {
        location: address.location,
        city
      })
      let [lng, lat] = address.location.split(',')
      this.onPullDownRefresh()
    })
  },
  getUserInfo(res) {
    if (res.detail.errMsg == "getUserInfo:ok") {
      let res_user = res.detail
      wx.login({
        success: function (res) {
          if (res.code) {
            let userInfo = res_user.userInfo
            let openId = wx.getStorageSync('openid')
            userInfo.openId = openId
            App.HttpService.saveUser(userInfo).then(res => {

            }, error => {})
          }
        }
      })
    } else {
      wx.showModal({
        title: '警告通知',
        content: '您点击了拒绝授权,将无法正常显示个人信息,点击确定重新获取授权。',
        success: function (res) {
          if (res.confirm) {
            wx.openSetting({
              success: (res) => {
                if (res.authSetting["scope.userInfo"]) { // 如果用户重新同意了授权登录
                  wx.login({
                    success: function (res_login) {
                      if (res_login.code) {
                        wx.getUserInfo({
                          withCredentials: true,
                          success: function (res_user) {
                            let userInfo = res_user.userInfo
                            let openId = wx.getStorageSync('openid')
                            userInfo.openId = openId
                            App.HttpService.saveUser(userInfo).then(res => {

                            }, error => {})
                          }
                        })
                      }
                    }
                  });
                }
              },
              fail: function (res) {}
            })
          }
        }
      })
      // app.getUserInfo()
    }
  },
  toFixed() { // 保养手册
    wx.navigateTo({
      url: '/pages/repair/index'
    })
  },
  reviews() {
    wx.navigateTo({
      url: '/pages/evaluate/index'
    })
  },
  toPackage() { // 套餐
    let defaultCar = wx.getStorageSync('defaultCar');
    if (defaultCar) {
      wx.navigateTo({
        url: '/pages/product/package/index'
      })
    } else {
      wx.navigateTo({
        url: '/pages/car/firstMenu/index'
      })
    }

  },
  toMore() { // 查看更多拼团
    wx.navigateTo({
      url: '/pages/group-buying/list/index'
    })
  },
  // 跳转到消息中心
  toMessageList(e) {
    wx.navigateTo({
      url: `/pages/messages/list/list`,
    })
  },
  // 跳转到评价中心
  toComments() {
    wx.navigateTo({
      url: '/pages/comments/list/list',
    })
  },
  // 跳转到个人中心
  toUser() {
    wx.navigateTo({
      url: '/pages/user/user',
    })
  },
  // 关闭优惠券和遮罩层
  closeCoupons() {
    this.setData({
      showCoupons: false
    });
    this.qingqiujingxi();
  },
  // 获取优惠券
  getCouponsList() {
    let agent = wx.getStorageSync('agent');
    let userId = wx.getStorageSync('userId');
    if (agent.id != '') {
      App.HttpService.couponsList({
        userId: userId,
        sellerId: agent.id
      }).then(res => {
        if (res.data.code == 200) {
          let data = res.data.data;
          if (data.length > 0) {
            this.setData({
              showCoupons: true,
              couponsList: data
            });
          } else {
            this.setData({
              showCoupons: false
            });
            this.qingqiujingxi();


          }
        }
      })
    }
  },
  // 领取优惠券
  receiveCoupons(e) {
    let couponsId = e.currentTarget.dataset.id;
    let arr = [];
    arr.push(couponsId);
    let userId = wx.getStorageSync('userId');
    App.HttpService.receiveCoupons({
      couponsIds: arr,
      userId
    }).then(res => {
      if (res.data.code == 200) {
        wx.showToast({
          title: '领取成功'
        })
        this.getCouponsList();
      }
    });
  },
  // 全部获取优惠券
  getAllCoupons(e) {
    let userId = wx.getStorageSync("userId");
    let arr = [];
    for (let i = 0; i < this.data.couponsList.length; i++) {
      arr.push(this.data.couponsList[i].id);
    }
    App.HttpService.receiveCoupons({
      couponsIds: arr,
      userId
    }).then(res => {
      if (res.data.code == 200) {
        wx.showToast({
          title: '领取成功'
        })
        this.getCouponsList();

      }
    })
  },
  // 获取首页评价
  getComments(index) {

    let sellerId = wx.getStorageSync('agent').id;
    //
    // 发起请求
    wx.showLoading({
      title: '加载中',
    })
    let brandId = wx.getStorageSync('agent').id
    // 

    App.HttpService.indexComments({
      sellerId,
      brandId: 0,
      page: index,
      pageCount: this.data.pageSize
    }).then(res => {
      console.log("66666666666666666666666666666666666666666", res)

      if (res.data.code == 200) {
        wx.hideLoading();
        var newData = {}
        if (res.data.data.revieList.length == 0) {
          // 没有数据了，已经是最后一页
          this.data.isLastPage = true
          this.data.tips = "已显示全部啦"
          return;
        }
        this.data.activeIndex = index + 1;
        // 追加数据
        // newData.revieList = 

        this.setData(newData)

        // let data = res.data.data;
        let commentsList = this.data.commentsList.concat(res.data.data.revieList);

        this.setData({
          commentsList
        });
      }
    });
  },
  onPullDownRefresh() {

    wx.showNavigationBarLoading()
    let position = wx.getStorageSync('position')
    let [lng, lat] = position.location.split(',')
    this.getAgent(lng, lat, () => {
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh()
    })

  },

  // 下拉触底事件
  onReachBottom() {

    if (this.data.page == 0) {
      this.data.activeIndex = 1;
      this.data.isLastPage = false;
    }
    // 最后一页了，取消下拉功能
    if (this.data.isLastPage) {
      return;
    }
    this.setData({
      page: this.data.page + 1
    })
    this.getComments(this.data.activeIndex)

  },
  onShareAppMessage() {
    let userId = wx.getStorageSync('userId');
    let sellerId = wx.getStorageSync("agent").id
    return {
      title: "扳子养车",
      path: `pages/index/index?userId=${userId}&sellerId=${sellerId}`
    }
  },
  // 输入手机号
  inputPhone(e) {
    let phone = e.detail.value;
    this.setData({
      phone
    });
  },
  // 输入验证码
  inputCode(e) {
    let code = e.detail.value;
    this.setData({
      code
    });
  },
  // 获取验证码
  getCode() {
    let phone = this.data.phone;
    let isSendCode = this.data.isSendCode;
    let sendCode = this.data.sendCode;
    if (phone == '') {
      wx.showToast({
        title: '请输入手机号',
        image: '../../assets/images/warning.png'
      })
      return false;
    }
    if (isSendCode) {
      return false;
    }
    App.HttpService.sendCode({
      phone
    }).then(res => {
      if (res.data.code == 200) {
        this.setData({
          isSendCode: true,
          sendCode: res.data.data
        });
        let second = 60;
        let timer = setInterval(() => {
          second--;
          this.setData({
            text: second + 's'
          });
          if (second == 0) {
            clearInterval(timer);
            this.setData({
              isSendCode: false,
              text: '获取验证码'
            });
          }
        }, 1000);
      }
    });
  },
  // 绑定手机号
  bindPhone() {
    let phone = this.data.phone;
    let code = this.data.code;
    let userId = wx.getStorageSync("userId");
    let invitationUserId = this.data.invitationUserId;
    let invitationSellerId = this.data.invitationSellerId;
    let heavyId = this.data.heavyId;
    if (phone == '') {
      wx.showToast({
        title: '请输入手机号',
        image: '../../assets/images/warning.png'
      })
      return false;
    }
    if (code == '') {
      wx.showToast({
        title: '请输入验证码',
        image: '../../assets/images/warning.png'
      })
      return false;
    }

    if (code != this.data.sendCode) {
      wx.showToast({
        title: '验证码错误',
        image: '../../assets/images/warning.png'
      })
      return false;
    }

    App.HttpService.bindPhone({
      phone,
      code,
      userId,
      invitationSellerId,
      invitationUserId,
      heavyId
    }).then(res => {

      if (res.data.code == 200) {
        this.setData({
          isShow: false
        });
        wx.showToast({
          title: '绑定成功',
        })
      }
    });
  },
  getheavyShop(heavyId) {
    console.log("开始验证大客户信息是否正确:" + heavyId);
    App.HttpService.heavyShop({
      heavyId
    }).then(res => {
      if (res.data.code == 200) {
        //如果返回成功，则将大客户ID更新到BuyerUser中
        let userId = wx.getStorageSync("userId");
        this.saveHeavyId(userId, heavyId);
      }
    });
  },
  saveHeavyId(userId, heavyId) {
    App.HttpService.saveHeavyId({
      userId,
      heavyId
    }).then(res => {
      if (res.data.code == 200) {
        console.log(res.data);
      }
    });
  },
  addfrom(e) {
    console.log('form', e)
    var that = this
    var formid = e.detail.formId
    let val = e.detail.value
    console.log(formid)
    this.fid(formid);

  },

  // 传送fromid
  fid: function (e) {
    // fromid
    let uid = wx.getStorageSync('userId')
    App.HttpService.fid({
      buyerId: uid,
      fromId: e
    }).then(res => {
      console.log(res)
    })
  },
  shishi: function (e) {
    console.log(e.detail.value)
    var a = e.detail.value;
    a = a.toUpperCase();
    console.log(a)
    this.setData({
      bang: a
    })

  },
  // 点击轮播图跳转
  tiaozdw: function (e) {
    console.log(e.currentTarget.dataset.url)
    var url = e.currentTarget.dataset.url
    var type = e.currentTarget.dataset.type


    if (type == 0) {
      if (url) {
        wx.navigateTo({
          url: '/pages/wenzhang/index?url=' + url,
        })
      }

    } else {
      if (url) {
        wx.navigateTo({
          url: url,
        })
      }

    }



  },
  getPhoneNumber: function (e) {

    console.log(e, "eeeeeee")
    var bz = e.detail.errMsg

    if (bz == "getPhoneNumber:ok") {
      console.log("获取成功")

      // user / check
      // App.HttpService.


    } else {
      console.log("获取失败")
    }


  },
  yaoqing: function () {
    this.setData({
      yaoqingyouli: false

    })
  },

  // 请求有没有八折保养 邀请也有奖

  qingqiujingxi: function () {
    App.HttpService.qingqiuhud({
      sellerId: wx.getStorageSync('agent').id,
      sbtid: this.data.sbtid

    }).then(res => {

      console.log(res)
      this.setData({
        sbtid: this.data.sbtid + 1
      })

      if (res.data.data == 0) {
        this.setData({
          qqhd: false
        })
      } else {
        this.setData({
          qqhd: true
        })
      }
    })
  },

  // 关闭邀请惊喜
  guanbiqq: function () {
    this.setData({
      qqhd: false,
      zxd: false

    })

  },

  baise: function () {
    console.log(666)
    wx.navigateTo({
      url: '/pages/product/package/index',
    })
    this.setData({
      qqhd: false,
      zxd: false
    })

  },
  baises: function () {



    wx.navigateTo({
      url: '/pages/fenxiangym/index',
    })
    this.setData({
      qqhd: false,
      zxd: false
    })

  }

})